package com.dayu.gulimall.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dayu.common.utils.PageUtils;
import com.dayu.common.utils.Query;
import com.dayu.gulimall.order.dao.OrderItemDao;
import com.dayu.gulimall.order.entity.OrderEntity;
import com.dayu.gulimall.order.entity.OrderItemEntity;
import com.dayu.gulimall.order.entity.OrderReturnReasonEntity;
import com.dayu.gulimall.order.service.OrderItemService;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Map;

@RabbitListener(queues = {"hello-java-queue"})
@Service("orderItemService")
public class OrderItemServiceImpl extends ServiceImpl<OrderItemDao, OrderItemEntity> implements OrderItemService {


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderItemEntity> page = this.page(
                new Query<OrderItemEntity>().getPage(params),
                new QueryWrapper<OrderItemEntity>()
        );

        return new PageUtils(page);
    }

    /**
     *
     * @param message 原生的消息详细信息，包括消息头+消息体
     * @param content 接收到的消息体<T>类型，
     * @param channel 连接的管道
     *                Queue：可以很多个服务来监听同一个消息队列，只要接收到消息，队列就删除消息，而且只能有一个队列接收到消息
     *                场景：
     *                  1、订单服务：服务订单启动多个，同一个消息只能有一个客户端接收到
     *                  2、只有一个消息处理完才会接收下一个消息
     */
//    @RabbitListener(queues = {"hello-java-queue"})
    @RabbitHandler
    public void receiveMessage(Message message, OrderReturnReasonEntity content, Channel channel) throws InterruptedException {

        System.out.println("接收到的消息："+message);
        byte[] body = message.getBody();
//        Thread.sleep(2000);
        //消息头信息
        MessageProperties messageProperties = message.getMessageProperties();

        //通道内按顺序消息自增
        long deliveryTag = messageProperties.getDeliveryTag();

        try {
            //是否批量签收
            channel.basicAck(deliveryTag,false);
        } catch (IOException e) {
            //断网
        }

        System.out.println("deliveryTag==>"+deliveryTag);
        System.out.println("消息消息处理完成："+content);
    }

    @RabbitHandler
    public void receiveMessage2(Message message, OrderEntity content, Channel channel) throws InterruptedException {
        System.out.println("消息消息"+content);
    }

}